﻿using CSRedis;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CsRedisSample.Infrastructure
{
    public class CsRedisCache
        : IDistributedCache, IDisposable
    {
        private readonly CsRedisOptions _options;
        private readonly CSRedisClient _client;
        public CsRedisCache(IOptions<CsRedisOptions> options)
        {
            _options = options.Value;
            _client = new CSRedisClient(_options.ConnectionString);

            RedisHelper.Initialization(_client);
        }

        public void Dispose()
        {
            _client.Dispose();
        }

        public byte[] Get(string key)
        {
            var str = _client.Get(key);
            return Encoding.UTF8.GetBytes(str);
        }

        public async Task<byte[]> GetAsync(string key, CancellationToken token = default(CancellationToken))
        {
            var str = await _client.GetAsync(key);
            return Encoding.UTF8.GetBytes(str);
        }

        public void Refresh(string key)
        {
            _client.Del(key);
        }

        public async Task RefreshAsync(string key, CancellationToken token = default(CancellationToken))
        {
            await _client.DelAsync(key);
        }

        public void Remove(string key)
        {
            _client.Del(key);
        }

        public async Task RemoveAsync(string key, CancellationToken token = default(CancellationToken))
        {
            await _client.DelAsync(key);
        }

        public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
        {
            _client.Set(key, Encoding.UTF8.GetString(value), options.AbsoluteExpirationRelativeToNow.Value.Seconds);
        }

        public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken))
        {
            await _client.SetAsync(key, Encoding.UTF8.GetString(value), options.AbsoluteExpirationRelativeToNow.Value.Seconds);
        }
    }
}
